import tkinter as tk
from tkinter import messagebox
a = [1,10,3,8,5,6,7,4,9,2]
str_array = ",".join(map(str, a))
def sub():

    n=10
    f=False
    txt2.delete(0,'end')
    try:
        key = int(txt1.get())
        
        if key % 2 ==1 :
            i = 0
        else:
            i = 1
        j = n-1
        f = False
        while i<=j and not f:
            if key % 2 == 0:
                m = (i+j)//2 -((i+j)//2  + 1)% 2
            else:
                m = (i+j)//2 - (i+j)//2  % 2
            if key==a[m]:
                f=True
            elif key % 2 == 0 and key>a[m] or key % 2 == 1 and key<a[m]:
                j = m-2
            else:
                i = m+2
        if f:
           txt2.insert(0,str(m+1))
        else:
           txt2.insert(0,"没有查找到！")
    except:        
       messagebox.showwarning('出错窗口','请输入一个正整数！')

#建立窗口
win =tk.Tk()
win.title('对分查找')
win.geometry("320x240") #默认窗口大小
#建立组件
lb1 = tk.Label(win,text = '对分查找数据：')
lb4 = tk.Label(win,text = '' + str_array)


lb2 = tk.Label(win,text = '输入对分查找数据：')
txt1 = tk.Entry(win,width=20,justify='center')
txt2 = tk.Entry(win,width=20,justify='center')
cmd = tk.Button(win, text = '对分查找', command = sub)
lb3 = tk.Label(win,text = '对分查找数据位置：')
#组件布局

lb1.grid(row=0, column = 0)
lb4.grid(row=0, column = 1)
lb2.grid(row=1, column = 0)
txt1.grid(row=1,column = 1)
lb3.grid(row=3, column = 0)
txt2.grid(row=3,column = 1)
cmd.grid(row=5,column = 1)

#接收窗口事件
win.mainloop()
